package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import com.itheima.transaction.MyTransactionManager;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.sql.Connection;

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
      private AccountDao accountDao;
   @Autowired
   private  MyTransactionManager myTransactionManager;
/*下面用的方式不好,每个方法都得添加事务控制,虽然具体事务操作已经简化,写在了专门的事务管理类中
*
* */

    @Override
    public void transfer(int from, int to, double money) {

        Connection connection=null;
        try {
            //开启事务
            connection=myTransactionManager .start();
          //业务逻辑正经的
            accountDao.add(to,money,connection);

            accountDao.sub(from,money,connection);

            //能走到这说明没有错误
            //提交事务
            myTransactionManager.commit(connection);
        }catch (Exception e){
            //回滚事务
            myTransactionManager.rollback(connection);
        }finally {
            //释放资源
            myTransactionManager.close(connection);
        }
    }

    @Override
    public void delete(int id) {
        Connection connection=null;
        try {
            //开启事务
            connection=myTransactionManager .start();

            accountDao.delete(id);

            //能走到这说明没有错误
            //提交事务
            myTransactionManager.commit(connection);
        }catch (Exception e){
            //回滚事务
            myTransactionManager.rollback(connection);
        }finally {
            //释放资源
            myTransactionManager.close(connection);
        }
    }


    @Override
    public void add(Account account) {

        accountDao.save(account);

    }

    @Override
    public Account findById(int id) {


        return accountDao.findById(id);
    }
}
